<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\CommonBase;
use think\facade\View;
use app\common\business\Category as CategoryBusiness;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class Article extends IndexBase
{
    private $_categoryBusiness = null;

    public function initialize()
    {
        parent::initialize();
        $this->_categoryBusiness = new CategoryBusiness($this->_websiteCode);
    }

    public function index(): string
    {
        View::assign(['cms' => $this->_getWebsiteMetaInfo(), 'isHome' => true]);
        return View::fetch('index_index');
    }

    public function cover($uri)
    {
        $attribute = $this->request->param('attribute', '', 'trim');
        $category  = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri, $attribute);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }
        // dump($category);exit;

        View::assign([
            'visitCid' => $category['id'],
            'cms'      => array_merge(
                ['category' => $category],
                $this->_getCategoryMetaInfo($category)
            ),
        ]);

        $tpl = $category['remark'] . '_' . $category['default_tpl'];
        return View::fetch($tpl);
    }

    public function lists($uri, $page)
    {
        $category = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }
        // dump($category);exit;

        View::assign([
            'visitCid' => $category['id'],
            'page'     => $page,
            'cms'      => array_merge(
                ['category' => $category],
                $this->_getCategoryMetaInfo($category)
            ),
        ]);

        $tpl = $category['remark'] . '_' . $category['list_tpl'];
        return View::fetch($tpl);
    }

    public function search()
    {
        $page = $this->request->get('p', 1, 'intval');
        $uri  = $this->request->get('uri');
        if ($uri == '') {
            $this->redirect('/');
        }

        $category = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }
        // dump($category);exit;

        View::assign([
            'visitCid' => $category['id'],
            'page'     => $page,
            'cms'      => array_merge(
                ['category' => $category],
                $this->_getCategoryMetaInfo($category)
            ),
        ]);

        $tpl = $category['remark'] . '_search';
        return View::fetch($tpl);
    }

    public function compare()
    {
        $post = $this->request->post();
        $uri  = $post['category_uri'] ?? '';
        if ($uri == '') {
            $this->redirect('/');
        }

        $aids = $post['aids'] ?? [];
        if (empty($aids)) {
            $this->redirect('/');
        }

        $category = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }
        // dump($category);exit;

        View::assign([
            'visitCid' => $category['id'],
            'cms'      => array_merge(
                ['category' => $category],
                $this->_getCategoryMetaInfo($category)
            ),
        ]);

        $tpl = $category['remark'] . '_compare';
        return View::fetch($tpl);
    }

    public function export()
    {
        $post = $this->request->post();
        $uri  = $post['category_uri'] ?? '';
        if ($uri == '') {
            $this->redirect('/');
        }

        $aids = $post['aids'] ?? [];
        if (empty($aids)) {
            $this->redirect('/');
        }

        $category = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }

        $moduleBusiness  = new \app\common\business\Module($this->_websiteCode);
        $module          = $moduleBusiness->findModuleById($category['module_id']);
        $articleBusiness = new \app\common\business\Article($this->_websiteCode, $module['code']);
        $articles        = $articleBusiness->getArticleList($this->cdnDomain, 1, count($aids), [['p.id', 'in', $aids]]);

        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();

        $styleContent = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color'       => ['argb' => '000000'],
                ],
            ],
        ];
        $styleTitle   = array_merge(
            $styleContent,
            [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                ],
                'font'      => [
                    'bold' => true,
                ],
            ]
        );

        foreach ($articles['rows'] as $i => $article) {
            $row = $i + 1;
            $sheet->getStyle(Coordinate::stringFromColumnIndex(1) . $row . ':' . Coordinate::stringFromColumnIndex(count($article['attributes']) + 1) . $row)->applyFromArray($styleTitle);

            $cell = Coordinate::stringFromColumnIndex(1) . $row;
            $sheet->getColumnDimension(Coordinate::stringFromColumnIndex(1))->setWidth(20);
            $sheet->setCellValue($cell, '型号');


            foreach ($article['attributes'] as $j => $attribute) {
                $col  = $j + 2;
                $cell = Coordinate::stringFromColumnIndex($col) . $row;
                $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($col))->setWidth(20);
                $sheet->setCellValue($cell, $attribute['attribute_name']);
            }

            break;
        }

        foreach ($articles['rows'] as $i => $article) {
            $row = $i + 2;
            $sheet->getStyle(Coordinate::stringFromColumnIndex(1) . $row . ':' . Coordinate::stringFromColumnIndex(count($article['attributes']) + 1) . $row)->applyFromArray($styleContent);

            $cell = Coordinate::stringFromColumnIndex(1) . $row;
            $sheet->setCellValue($cell, $article['title']);

            foreach ($article['attributes'] as $j => $attribute) {
                $col  = $j + 2;
                $cell = Coordinate::stringFromColumnIndex($col) . $row;
                $sheet->setCellValue($cell, $attribute['attribute_value_remark']);
            }
        }

        $writer   = new Xlsx($spreadsheet);
        $fileName = '产品导出-' . date('Y-m-d') . '.xlsx';
        $tempPath = './upload/' . $fileName;
        $writer->save($tempPath);

        // 设置 HTTP 响应头，告诉浏览器该文件类型为 Excel
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        readfile($tempPath);

        @unlink($tempPath);
    }

    public function view($uri, $articleId)
    {
        $category = $this->_categoryBusiness->findCategoryByUri($this->cdnDomain, $uri);
        if (empty($category)) {
            return redirect((string)url('permission/404'));
        }

        $moduleBusiness = new \app\common\business\Module($this->_websiteCode);
        $module         = $moduleBusiness->findModuleById($category['module_id']);
        if (empty($module) || $module['status'] == CommonBase::IS_DISABLE_STATUS) {
            return redirect((string)url('permission/500'));
        }
        $categoryCreateAtStr = date('Ymd', strtotime($category['created_at']));
        $aid                 = intval(str_replace($categoryCreateAtStr, '', $articleId));
        $articleBusiness     = new \app\common\business\Article($this->_websiteCode, $module['code']);
        $article             = $articleBusiness->findArticleById($this->cdnDomain, $aid, $this->_categoryBusiness->getCategories());
        // dump($article);exit;
        // dump($category);exit;

        View::assign([
            'visitCid' => $category['id'],
            'visitAid' => $aid,
            'cms'      => array_merge(
                ['category' => $category, 'article' => $article],
                $this->_getArticleMetaInfo($article, $category)
            ),
        ]);

        $tpl = $category['remark'] . '_' . $category['view_tpl'];
        return View::fetch($tpl);
    }

    public function download()
    {
        $file = $this->request->param('file');
        if ($file == '') {
            $this->redirect('/');
        }

        $file = base64_decode($file);

        $name = $this->request->param('name');
        if ($name == '') {
            $this->redirect('/');
        }

        $fileInfo = pathinfo($file);
        if (!isset($fileInfo['extension'])) {
            $this->redirect('/');
        }

        $fileContent = file_get_contents($file);
        if ($fileContent == '') {
            $this->redirect('/');
        }

        $ext      = $fileInfo['extension'];
        $fileName = sprintf("%s.%s", $name, $ext);
        header("Content-Type: application/octet-stream");
        header('Content-Disposition:attachment;filename="' . $fileName . '"');
        echo $fileContent;

        exit;
    }

    private function _getCategoryMetaInfo(array $category): array
    {
        $websiteMetaInfo = $this->_getWebsiteMetaInfo();
        $parents         = $this->_categoryBusiness->getCurCategoryParents($category['id']);
        $metaTitles      = [];
        $breadcrumbs     = [];
        for ($i = count($parents) - 1; $i >= 0; $i--) {
            $metaTitles [] = $parents[$i]['title'];
            $breadcrumbs[] = [
                'title' => $parents[$i]['title'],
                'url'   => $this->_categoryBusiness->getCategoryUrl($parents[$i]['id']),
            ];
        }
        $metaTitles[] = $websiteMetaInfo['metaTitle'];
        $metaTitle    = implode('-', $metaTitles);

        return [
            'topCategory'     => count($parents) > 0 ? $parents[count($parents) - 1] : [],
            'breadcrumbs'     => $breadcrumbs,
            'metaTitle'       => !empty($category['meta_title']) ? $category['meta_title'] : $metaTitle,
            'metaKeyword'     => !empty($category['meta_keyword']) ? $category['meta_keyword'] : $websiteMetaInfo['metaKeyword'],
            'metaDescription' => !empty($category['meta_description']) ? $category['meta_description'] : $websiteMetaInfo['metaDescription'],
        ];
    }

    private function _getArticleMetaInfo(array $article, array $category): array
    {
        $websiteMetaInfo = $this->_getWebsiteMetaInfo();
        $parents         = $this->_categoryBusiness->getCurCategoryParents($category['id']);
        $breadcrumbs     = [];
        for ($i = count($parents) - 1; $i >= 0; $i--) {
            $breadcrumbs[] = [
                'title' => $parents[$i]['title'],
                'url'   => $this->_categoryBusiness->getCategoryUrl($parents[$i]['id']),
            ];
        }
        return [
            'topCategory'     => count($parents) > 0 ? $parents[count($parents) - 1] : [],
            'breadcrumbs'     => $breadcrumbs,
            'metaTitle'       => !empty($article['meta_title']) ? $article['meta_title'] : $article['title'] . '-' . $websiteMetaInfo['metaTitle'],
            'metaKeyword'     => !empty($article['meta_keyword']) ? $article['meta_keyword'] : $websiteMetaInfo['metaKeyword'],
            'metaDescription' => !empty($article['meta_description']) ? $article['meta_description'] : $websiteMetaInfo['metaDescription'],
        ];
    }
}
